/*
 * Copyright (C) 2008 Jens Meiß
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 *
 */
package com.googlecode.hmvc4gwt.example.hmvcblog.frontend.blog.client;

import com.google.gwt.user.client.History;
import com.googlecode.hmvc4gwt.example.hmvcblog.frontend.blog.client.blog.BlogController;
import com.googlecode.hmvc4gwt.example.hmvcblog.frontend.blog.client.blog.BlogModel;
import com.googlecode.hmvc4gwt.example.hmvcblog.frontend.blog.client.blog.BlogView;
import com.googlecode.hmvc4gwt.example.hmvcblog.frontend.blog.client.blog.events.in.ShowBlogViewEvent;
import com.googlecode.hmvc4gwt.example.hmvcblog.frontend.historytoken.client.HistoryToken;
import com.googlecode.hmvc4gwt.framework.client.module.AModuleControllerRegistry;
import com.googlecode.hmvc4java.component.Component;
import com.googlecode.hmvc4java.event.IEvent;
import com.googlecode.hmvc4java.event.TerminateEvent;

public class Blog extends AModuleControllerRegistry {

	public void handleEventImpl(IEvent event) {
	}

	public void initImpl() {
	}

	public void terminateImpl() {
	}

	public void onHistoryChanged(String historyToken) {
		
		if (historyToken.matches( "^" + HistoryToken.blog + "=[0-9]+$")) {
			
			try {
				int blogId = Integer.parseInt(historyToken.substring(HistoryToken.blog.length() + 1));
				showBlog(blogId);
			} catch (Exception e) {
				History.newItem(HistoryToken.bloglist);
			}
		} 
		
	}

	private void showBlog(int blogId) {
		
		fireEventDown(new TerminateEvent());
		if (!getComponent().containsChildComponent(BlogController.class)) {
			addChildComponent(new Component(new BlogModel(blogId), new BlogView(), new BlogController()));
		}
				
		fireEventDown(new ShowBlogViewEvent());
		
	}
}
 